'use strict';

const {
	Controller
} = require('uni-cloud-router');
const dbcmd = uniCloud.database().command;
const $ = dbcmd.aggregate;

module.exports = class MemberDetailController extends Controller {
	// 用户数据
	async data() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		};

		const start = Date.now();
		const {
			uid
		} = this.ctx.data;

		if (!uid) {
			this.throw('查询用户不存在');
		}

		// 查询用户
		const dataRes = await this.db.collection('usemall-member')
			.doc(uid)
			.field({
				member_nickname: true,
				member_headimg: true,
				member_gender: true,
				member_monetary: true,
				member_amount: true,
				member_login_cnt: true,
				member_coupon_cnt: true,
				member_login_current_ip: true,
				member_city: true,
				create_time: true,
				last_modify_time: true
			})
			.get();

		// 查询汇总数据
		const totalRes = await this.total();
		response.datas.total = totalRes.datas;

		const [data] = dataRes.data;
		response.datas.detail = data;

		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.duration = `耗时：${end - start}ms`;
		return response;
	}

	// 汇总数据
	async total() {
		let response = {
			code: 1,
			datas: null,
			msg: ''
		};

		const start = Date.now();
		const {
			uid
		} = this.ctx.data;

		// 查询数据数
		const orderRes = this.db.collection('usemall-order').where({
			is_delete: 0,
			create_uid: uid
		}).field({
			_id: true
		}).count();
		const footprintRes = this.db.collection('usemall-goods-history').where({
			create_uid: uid
		}).field({
			_id: true
		}).count();
		const collectRes = this.db.collection('usemall-member-collect').where({
			create_uid: uid
		}).field({
			_id: true
		}).count();
		const addressRes = this.db.collection('usemall-member-address').where({
			create_uid: uid
		}).field({
			_id: true
		}).count();
		const walletRes = this.db.collection('usemall-member-money-log').where({
			create_uid: uid
		}).field({
			_id: true
		}).count();
		const couponRes = this.db.collection('usemall-marketing-coupon').where({
			create_uid: uid
		}).field({
			_id: true
		}).count();
		const integralRes = this.db.collection('usemall-integral-record').where({
			create_uid: uid
		}).field({
			_id: true
		}).count();

		const res = await Promise.all([
			orderRes,
			footprintRes,
			collectRes,
			addressRes,
			walletRes,
			couponRes,
			integralRes
		]);

		response.datas = {
			order_cnt: res[0].total,
			footprint_cnt: res[1].total,
			collect_cnt: res[2].total,
			address_cnt: res[3].total,
			wallet_cnt: res[4].total,
			coupon_cnt: res[5].total,
			integral_cnt: res[6].total
		};

		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.duration = `耗时：${end - start}ms`;
		return response;
	}

	// 查询订单
	async orderGet() {
		let response = {
			code: 1,
			datas: null,
			msg: ''
		};

		const start = Date.now();
		const {
			uid,
			// 分组统计
			group,
			state,

			page = 1,
			rows = 10,
			orderby = 'create_time desc'
		} = this.ctx.data;

		if (!uid) {
			this.throw('查询用户不存在');
		}

		// 查询指定用户订单
		let whereObj = {
			is_delete: 0,
			create_uid: uid
		};

		if (state && state !== '全部') {
			// 订单状态
			whereObj.state = state;
		}

		if (group && group.field) {
			let groupWhereObj = Object.assign({}, whereObj);
			delete groupWhereObj[group.field];

			const groupRes = await this.db.collection('usemall-order')
				.aggregate()
				.match(groupWhereObj)
				.group({
					_id: '$' + group.field,
					cnt: $.sum(1)
				})
				.end();

			if (groupRes && groupRes.data) {
				response.groupDatas = groupRes.data;
				group.datas = [];
				group.total = 0;

				for (let key in group.obj) {
					group.obj[key] = 0;
				}

				response.groupDatas.forEach(x => {
					if (Object.keys(group.obj).includes(x._id + "")) {
						group.obj[x._id] = x.cnt;
						group.total += x.cnt;
					}
				})
				if (Object.keys(group.obj).includes('全部')) {
					group.obj['全部'] = group.total;
				}

				for (let key in group.obj) {
					group.datas.push({
						name: key,
						cnt: group.obj[key]
					})
				}
				response.group = group;
			}
		}

		// 排序规则
		const [field, sort] = orderby.split(' ');
		// 查询用户订单
		const dataRes = await this.db.collection('usemall-order')
			.where(whereObj)
			.orderBy(field, sort)
			.skip((page - 1) * rows)
			.limit(rows)
			.field({
				order_id: true,
				order_member_headimg: true,
				order_member_name: true,
				create_time: true,
				order_total_money: true,
				order_total_money: true,
				order_total_cnt: true,
				order_from: true,
				state: true,
				order_pay_way: true,
				order_pay_state: true,
				order_actural_paid: true
			})
			.get();

		const datas = [];
		const ids = dataRes.data.map(x => x.order_id);
		if (ids.length) {
			// 订单详情
			const subDataRes = await this.db.collection('usemall-order-detail')
				.where({
					order_id: dbcmd.in(ids)
				})
				.limit(ids.length)
				.field({
					order_id: true,
					goods_id: true,
					goods_name: true,
					goods_name_pw: true,
					goods_img: true,
					goods_num: true,
					goods_price: true,
					goods_market_price: true,
					goods_price_tag: true,
					goods_tejia: true,
					goods_sku: true,
					goods_sku_name: true,
					goods_type: true
				})
				.get();

			// 数据组合
			dataRes.data.forEach(x => {
				const subDatas = subDataRes.data.filter(s => s.order_id === x.order_id);
				datas.push({
					...x,
					order_details: subDatas
				});
			});
		}
		response.datas = datas;

		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.duration = `耗时：${end - start}ms`;
		return response;
	}

	// 过滤特殊字符
	filterRegexpKey(str) {
		if (!str) return '';

		str += '';

		const arr = ['\\', '$', '(', ')', '*', '+', '.', '[', ']', '?', '^', '{', '}', '|'];

		arr.forEach(x => {
			str = str.replace(new RegExp(`\\${x}`), `\\${x}`);
		});

		return str;
	}
}